package org.fjsei.yewu.controller;

import lombok.extern.slf4j.Slf4j;
import org.fjsei.yewu.resolver.TusFileUploadResolver;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class XhrUploadController {
    @jakarta.annotation.Resource
    private TusFileUploadResolver tusFileUploadResolver;

    /**
     * 支持 XHRUpload 的普通 HTTP 文件上传端点
     * 超大文件请用TUS，因为它：支持分片上传，支持断点续传，内存使用更友好，网络中断后可以恢复；
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> xhrUpload(
            @RequestParam("files[]") MultipartFile[] files,
            @RequestParam("business") String business,
            @RequestParam("eid") String eid,
            @RequestParam("liveDays") int liveDays,
            @RequestParam("name") String fileName,
            @RequestParam(value = "relativePath", required = false) String relativePath,
            @RequestParam("type") String fileType,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        List<Map<String, Object>> uploadedFiles = new ArrayList<>();

        try {
            // 记录接收到的元数据
            log.info("上传元数据 - eid: {}, liveDays: {}, fileName: {}, relativePath: {}, fileType: {}",
                    eid, liveDays, fileName, relativePath, fileType);
            if (files == null || files.length == 0) {
                response.put("error", "没有接收到文件");
                return ResponseEntity.badRequest().body(response);
            }
            //处理多个文件，但uppy实际每次请求都只有一个文件！文件大小限制在配置文件 max-request-size=500MB
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    try {
                        // 使用 TusFileUploadResolver 中的 MinIO 上传逻辑，传递元数据
                        String fileUrl = tusFileUploadResolver.uploadToMinIOWithMeta(file,business, eid, liveDays, fileName);

                        if (fileUrl != null) {
                            Map<String, Object> fileInfo = new HashMap<>();
                            fileInfo.put("name", file.getOriginalFilename());
                            fileInfo.put("url", fileUrl); // 这里返回的是 bucketName/objectName 格式的 ID
                            fileInfo.put("size", file.getSize());
                            fileInfo.put("type", file.getContentType());
                            // 添加自定义元数据到响应
                            fileInfo.put("business", business);
                            fileInfo.put("eid", eid);
                            fileInfo.put("liveDays", liveDays);
                            uploadedFiles.add(fileInfo);
                            log.info("XHR 上传成功: {} -> {}, eid: {}", file.getOriginalFilename(), fileUrl, eid);
                        }
                    } catch (Exception e) {
                        log.error("单个文件上传失败: {}", file.getOriginalFilename(), e);
                        Map<String, Object> errorFile = new HashMap<>();
                        errorFile.put("name", file.getOriginalFilename());
                        errorFile.put("error", e.getMessage());
                        uploadedFiles.add(errorFile);
                    }
                }
            }

            if (uploadedFiles.isEmpty()) {
                response.put("error", "所有文件上传都失败了");
                return ResponseEntity.status(500).body(response);
            }

            response.put("successful", uploadedFiles);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("XHR 文件上传失败", e);
            response.put("error", "上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

//    @PostMapping("/upload/single")
//    public ResponseEntity<Map<String, Object>> xhrUploadSingle(
//            @RequestParam("file") MultipartFile file,
//            HttpServletRequest request) {
//        MultipartFile[] files = new MultipartFile[]{file};
//        return xhrUpload(files, request);
//    }

}